package net.borlis.configuration.properties;

import net.borlis.configuration.common.ConfigurationInitError;
import net.borlis.configuration.common.DatabaseDriver;
import net.borlis.configuration.common.StandardConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The dynamix config tool configuration object.
 *
 * @author alex@borlis.net
 */
@ApplicationScoped @PropertiesData @Deprecated
public class PropertiesFileConfiguration extends StandardConfiguration {

    @Inject
    private Logger logger;
    //-=-=-=-
    private PropertiesConfiguration configuration;
    //-=-=-=

    public PropertiesConfiguration getConfiguration() {
        return configuration;
    }

    public void initJdbc() {
        setDriverName(getConfiguration().getString("database.driver"));
        final String urlPrefix;
        if (DatabaseDriver.MYSQL_DRIVER.getDriverName().equals(getDriverName())) {
            urlPrefix = "jdbc:mysql://";
        } else {
            throw new IllegalStateException("unknown db driver");
        }
        setSchemaVersion(getConfiguration().getString("schema.version"));

        setServer(getConfiguration().getString("database.server"));
        setPort(getConfiguration().getString("database.port"));

        setJdbcUrl(urlPrefix + getServer() + ":" + getPort() + "/" + getSchemaVersion() + "_");
        setJdbcUser(getConfiguration().getString("database.user"));
        setJdbcPassword(getConfiguration().getString("database.password"));
        setAutoUpdate(getConfiguration().getBoolean("database.autoUpdate"));
    }

    /**
     * Init the configuration with the provided configuration file.
     */
    @PostConstruct
    public void init() {
        try {
            logger.info("configuration loading started");
            configuration = new PropertiesConfiguration("dpct.properties");
            logger.info("configuration = " + configuration);
            initJdbc();
            initEncryptionService();
            initAuthClient();
            logger.info("configuration loading finished");
        } catch (Exception cex) {
            logger.log(Level.SEVERE, cex.getMessage(), cex);
            throw new ConfigurationInitError(cex);
        }
    }

    private void initEncryptionService() {
        setEncryptionServiceLogin(getConfiguration().getString("encryptionService.login"));
        setEncryptionServicePassword(getConfiguration().getString("encryptionService.password"));
        setEncryptionServiceURL(getConfiguration().getString("encryptionService.url"));
    }

    private void initAuthClient() {
        setClientKey(getConfiguration().getString("auth.clientKey"));
    }

}
